<template>
  <a-form :form="form" :label-col="{ span: 1 }" :wrapper-col="{ span: 23 }" @submit.prevent="handleSubmit">
    <a-form-item label=" " :colon="false">
      <Variable />
    </a-form-item>
    <a-form-item label="正文">
      <a-textarea
        :auto-size="{ minRows: 10 }"
        v-decorator="[
          'email_content',
          {
            initialValue: data.email_content,
            rules: [{ required: true, message: 'Please input your note!' }] }]"
      />
    </a-form-item>
    <a-form-item :wrapper-col="{ span: 12, offset: 0 }">
      <a-button type="primary" html-type="submit" :loading="state.btn" @click.prevent="handleSubmit">
        保存
      </a-button>

      <a-button class="cancel-button">取消</a-button>
    </a-form-item>
  </a-form>
</template>

<script>
import { modifyTemplate } from '@/api/flow/admin_message'
import Variable from './Variable.vue'
import props from './props'

export default {
  mixins: [props],

  components: {
    Variable,
  },

  data () {
    return {
      formLayout: 'horizontal',
      form: this.$form.createForm(this, { name: 'coordinated' }),

      // state
      state: {
        btn: false,
      },
    }
  },
  methods: {
    // submit
    handleSubmit () {
      const {
        form: { validateFields, getFieldsValue },
        state,
      } = this

      state.btn = true

      this.validateFieldsForm()
        .then(() => {
          this.submitForm()
            .then((res) => {
              this.$notification.success({
                message: '修改成功!',
                duration: 1,
              })
              // this.SubmitSuccess(res);
            })
            .finally(() => {
              state.btn = false
            })
        })
        .catch(() => {
          state.btn = false
        })
    },

    submitForm () {
      const validateFieldsKey = ['email_content']

      return new Promise((resolve, reject) => {
        const fields = this.form.getFieldsValue(validateFieldsKey)

        modifyTemplate({ ...fields, tid: this.id })
          .then((data) => {
            resolve(data)
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

    validateFieldsForm () {
      return new Promise((resolve, reject) => {
        const {
          form: { validateFieldsAndScroll },
        } = this

        validateFieldsAndScroll((err, values) => {
          if (!err) {
            resolve()
            return false
          }
          reject(false)
        })
      })
    },
  },
}
</script>

<style lang="scss" scoped>

.cancel-button {
  margin-left: $margin-sm;
}
</style>
